from flask import Blueprint, request, jsonify
from flaskapp.util.Sqlalchemy import db
from flaskapp.entity.Appointment import Appointment
from flaskapp.entity.House import House
from flaskapp.entity.User import User  # 假设有这个实体类
from flaskapp.util.Redprint import Redprint
from datetime import datetime

api = Redprint('appointment')

# 创建预约
@api.route('/create', methods=['POST'])
def create_appointment():
    data = request.get_json()
    client_id = data.get('client_id')
    house_id = data.get('house_id')
    landlord_id = data.get('landlord_id')
    appointment_time = data.get('appointment_time')

    if not all([client_id, house_id, landlord_id, appointment_time]):
        return jsonify({'code': 400, 'message': '缺少必要参数'})

    try:
        appointment = Appointment(
            client_id=client_id,
            house_id=house_id,
            landlord_id=landlord_id,
            appointment_time=datetime.strptime(appointment_time, '%Y-%m-%d %H:%M:%S')
        )
        db.session.add(appointment)
        db.session.commit()
        return jsonify({'code': 200, 'message': '预约成功'})
    except Exception as e:
        db.session.rollback()
        print(e)
        return jsonify({'code': 500, 'message': str(e)})


# 取消预约
@api.route('/cancel/<int:appointment_id>', methods=['PUT'])
def cancel_appointment(appointment_id):
    try:
        appointment = Appointment.query.get(appointment_id)
        if not appointment:
            return jsonify({'code': 404, 'message': '预约不存在'})
        appointment.status = 3  # 已取消
        db.session.commit()
        return jsonify({'code': 200, 'message': '取消成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': str(e)})


# 接受/拒绝预约
@api.route('/process', methods=['PUT'])
def process_appointment():
    data = request.get_json()
    appointment_id = data.get('appointment_id')
    status = data.get('status')  # 1:接受，2:拒绝

    if status not in [1, 2]:
        return jsonify({'code': 400, 'message': '无效的状态值'})

    try:
        appointment = Appointment.query.get(appointment_id)
        if not appointment:
            return jsonify({'code': 404, 'message': '预约不存在'})
        appointment.status = status
        db.session.commit()
        return jsonify({'code': 200, 'message': '处理成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': str(e)})


# 查询我的预约（租客）
@api.route('/client/<int:client_id>', methods=['GET'])
def get_client_appointments(client_id):
    try: 
        print(client_id)
        appointments = db.session.query(Appointment, House).join(
            House, Appointment.house_id == House.house_id
        ).filter(Appointment.client_id == client_id).all()

        result = [{
            **appointment.to_dict(),
            'house': house.to_dict()
        } for appointment, house in appointments]
        print(result)
        return jsonify({'code': 200, 'data': result})
    except Exception as e:
        return jsonify({'code': 500, 'message': str(e)})


# 查询待处理/全部预约（房东）
@api.route('/landlord/<int:landlord_id>', methods=['GET'])
def get_landlord_appointments(landlord_id):
    try:
        status = request.args.get('status', type=int)  # 可选参数：status=0 表示仅查待处理
        query = db.session.query(Appointment, House, User).join(
            House, Appointment.house_id == House.house_id
        ).join(
            User, Appointment.client_id == User.user_id
        ).filter(Appointment.landlord_id == landlord_id)

        if status is not None:
            query = query.filter(Appointment.status == status)

        appointments = query.all()

        result = [{
            **appointment.to_dict(),
            'house': house.to_dict(),
            'client_name': user.account_name
        } for appointment, house, user in appointments]

        return jsonify({'code': 200, 'data': result})
    except Exception as e:
        return jsonify({'code': 500, 'message': str(e)})
